from twisted.cred import error, credentials, checkers
from twisted.python import failure
from twisted.internet import defer
from zope import interface
import sha

class _Users(dict):
    interface.implements(checkers.ICredentialsChecker)

# MW don't know what this is for
    credentialInterfaces = (credentials.IUsernamePassword,)

    def hash(self,passwd):
        return sha.sha(passwd).digest()

    def findUsername(self,person):
        if self.has_key(person.id()):
            return self[person.id()]
        return None

    def addUser(self,user,password,personid):
        self[personid] = user
        if password is None:
            return
        self[user] = (self.hash(password),personid)
        
    def _cbPasswordMatch(self, matched, personid):
        print "PASSWORDMATCH:",personid
        if matched:
            return personid
        return failure.Failure(error.UnauthorizedLogin())

    def requestAvatarId(self, credentials):
        print "CHECKING",credentials.username,credentials.password
        credentials.password = self.hash(credentials.password)
        if credentials.username in self:
            print "  username exists"
            return defer.maybeDeferred(
                credentials.checkPassword,
                self[credentials.username][0]).addCallback(
                self._cbPasswordMatch, self[credentials.username][1])
        else:
            return failure.Failure(error.UnauthorizedLogin())
    
Users = _Users()
